<template>
  <div>
    <h3>分类参数</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <!-- 选择商品分类的级联选择框 -->
      <el-row class="cat_opt">
        <!-- 参数级联选择 -->
        <el-col :span="12">
          <el-form>
            <el-form-item label="选择商品分类:">
              <el-cascader
                expandTrigger="hover"
                v-model="selectedCateKeys"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col>
          <!-- tab页签区域 -->
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数的面板 将标签页改为many -->
            <el-tab-pane label="动态参数" name="many">
              <el-button
                size="mini"
                type="primary"
                :disabled="isButtonDisabled"
                @click="showAddParamdialog"
                >添加参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyTableData" border stripe>
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="sc">
                    <!-- {{ sc.row.attr_vals }} -->
                    <el-tag
                      v-for="(item, ind) in sc.row.attr_vals"
                      :key="ind"
                      closable
                      @close="handleClose(ind, sc.row)"
                    >
                      {{ item }}
                    </el-tag>

                    <!-- 新增输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="sc.row.inputVisible"
                      v-model="sc.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(sc.row)"
                      @blur="handleInputConfirm(sc.row)"
                    >
                    </el-input>
                    <!-- 新增按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(sc.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                  label="参数名称"
                  prop="attr_name"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParamsFn(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加静态属性的面板 将标签页改为only -->
            <el-tab-pane label="静态属性" name="only">
              <el-button
                size="mini"
                type="primary"
                :disabled="isButtonDisabled"
                @click="showAddParamdialog"
                >添加属性</el-button
              >
              <!-- 静态属性表格 -->
              <el-table :data="onlyTableData" border stripe>
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="sc">
                    <!-- {{ sc.row.attr_vals }} -->
                    <el-tag
                      v-for="(item, ind) in sc.row.attr_vals"
                      :key="ind"
                      closable
                      @close="handleClose(ind, sc.row)"
                    >
                      {{ item }}
                    </el-tag>

                    <!-- 新增输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="sc.row.inputVisible"
                      v-model="sc.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(sc.row)"
                      @blur="handleInputConfirm(sc.row)"
                    >
                    </el-input>
                    <!-- 新增按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(sc.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                  label="属性名称"
                  prop="attr_name"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParamsFn(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加参数或属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsFlag"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsFlag = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态属性、静态属性对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editParamsFlag"
      width="50%"
      @close="resetEditParamForm"
    >
      <!-- 添加表单 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditParamForm">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCateListAPI,
  getParamsListAPI,
  addParamAPI,
  deleteParamsByIdAPI,
  editParamsByIdAPI
} from '@/api'
export default {
  data() {
    return {
      // 分类列表
      cateList: [],
      // 用户在级联下拉菜单中选中的分类id
      selectedCateKeys: [],
      // 配置级联菜单中数据如何展示
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      // 用来保存动态参数数据
      manyTableData: [],
      // 用来保存静态属性数据
      onlyTableData: [],
      addParamsFlag: false,
      titleText: '动态参数',
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      editParamsFlag: false,
      editForm: {
        id: -1,
        attrId: -1,
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 添加计算属性用来获取按钮禁用与否
    isButtonDisabled() {
      return this.selectedCateKeys.length !== 3
    },
    // 获取选中的三级分类id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[this.selectedCateKeys.length - 1]
      }
      return null
    }
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      // 获取所有的商品分类列表
      const { data: res } = await getCateListAPI()

      //   console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      // 将数据列表赋值给cateList
      this.cateList = res.data
      // //保存总数据条数
      // this.total = res.data.total
      //   console.log(res.data);
    },
    // 级联选框改变事件
    handleChange() {
      // 当用户在级联菜单中选择内容改变时触发
      //   console.log(this.selectedCateKeys)
      this.getParamsList()
    },
    // 级联选择框改变后查询当前分类的动态参数与静态属性列表
    async getParamsList() {
      // 发送请求，根据用户选择的三级分类和面板获取参数数据
      const { data: res } = await getParamsListAPI({
        id: this.cateId,
        sel: this.activeName
      })
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表数据失败')
      }

      res.data.forEach(v => {
        v.inputVisible = false
        v.inputValue = ''
        v.attr_vals = v.attr_vals ? v.attr_vals.split(',') : []
      })

      //   console.log(res.data)
      if (this.activeName === 'many') {
        // 获取的是动态参数
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        // 获取的是静态属性
        this.onlyTableData = res.data
      }
    },
    // 标签页选项点击
    handleTabClick() {
      console.log(this.activeName)
      this.activeName === 'many'
        ? (this.titleText = '动态参数')
        : (this.titleText = '静态参数')
      this.handleChange()
    },
    // 打开新增弹框
    showAddParamdialog() {
      this.addParamsFlag = true
    },
    // 关闭新增弹框
    addDialogClosed() {
      this.addParamsFlag = false
      this.addForm.attr_name = ''
    },
    addParams() {
      // 当用户点击对话框中的确定时，校验表单
      this.$refs.addParamsFormRef.validate(async valid => {
        // 校验不通过，return
        if (!valid) return
        // 校验通过，发送请求完成添加参数或者属性
        const { data: res } = await addParamAPI({
          id: this.cateId,
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: 'a,b,c'
        })
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.titleText + '数据失败')
        }
        this.$message.success('添加' + this.titleText + '数据成功')
        this.addParamsFlag = false
        this.getParamsList()
      })
    },
    // 删除参数
    async deleteParamsFn(arrtId) {
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      if (result === 'cancal') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }

      const { data: res } = await deleteParamsByIdAPI(this.cateId, arrtId)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsList()
    },
    // 打开编辑框
    showEditDialog(row) {
      //   console.log(row)
      this.editParamsFlag = true
      this.editForm.attr_name = row.attr_name
      this.editForm.attrId = row.attr_id
      this.editForm.attr_sel = row.attr_sel
      this.editForm.attr_vals = row.attr_vals.join(',')
      this.editForm.id = row.cat_id
    },
    // 重置编辑框
    resetEditParamForm() {
      this.editParamsFlag = false
      this.editForm.attr_name = ''
      this.editForm.attrId = -1
      this.editForm.attr_sel = ''
      this.editForm.attr_vals = ''
      this.editForm.id = -1
    },
    // 修改保存
    editParams() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await editParamsByIdAPI({
          ...this.editForm
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.resetEditParamForm()
        this.getParamsList()
      })
    },
    // el-tag 文本框enter事件
    handleInputConfirm(row) {
      // 输入内容为空，不需要后续操作
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 把修改后的数据保存到数据库中
      this.saveAttrVals(row)
    },

    // 点击新增tag按钮显示新增输入框
    showInput(row) {
      row.inputVisible = true
      // $nextTick : 当页面上元素被重新渲染后才执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击el-tag上的X
    handleClose(ind, row) {
      //   console.log(ind)
      //   console.log(row)
      row.attr_vals.splice(ind, 1)
      this.saveAttrVals(row)
    },
    // 修改attr_val后进行保存数据 ， 单独抽离出一个方法
    async saveAttrVals(row) {
      // 进行数据保存
      const { data: res } = await editParamsByIdAPI({
        id: row.cat_id,
        attrId: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })

      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message({
        message: res.meta.msg,
        type: 'success'
      })
    }
  }
}
</script>

<style scoped>
.el-cascader {
  width: 80%;
  margin: 10px 0;
}
.el-tag {
  margin: 0 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
